package com.zhuifeng.orders.service.impl;

import com.alibaba.fastjson2.JSON;
import com.zhuifeng.orders.domain.Provinces;
import com.zhuifeng.orders.mapper.ProvincesMapper;
import com.zhuifeng.orders.service.ProvincesService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ProvincesServiceImpl implements ProvincesService {
    private final ProvincesMapper provincesMapper;

    private final StringRedisTemplate redisTemplate;

    private final RedissonClient redissonClient;

    public ProvincesServiceImpl(ProvincesMapper provincesMapper, StringRedisTemplate redisTemplate, RedissonClient redissonClient) {
        this.provincesMapper = provincesMapper;
        this.redisTemplate = redisTemplate;
        this.redissonClient = redissonClient;
    }

    @Override
    public List<Provinces> findByProvincesId() {
//        获取锁
        RLock lock = redissonClient.getLock("order:provinces");
//        第一次判断redis
        if (redisTemplate.hasKey("provincesList")) {
            System.out.println("访问redis");
            return JSON.parseArray(redisTemplate.opsForValue().get("provincesList"),Provinces.class);
        }

        try {
//            加锁
            lock.tryLock(300,3000, TimeUnit.MINUTES);
//            加锁后再次判断redis
            System.out.println("上锁");
            if (!redisTemplate.hasKey("provincesList")) {
//                查询数据库
                List<Provinces> byProvincesId = provincesMapper.findByProvincesId();
//                存入redis
                System.out.println("访问数据");
                redisTemplate.opsForValue().set("provincesList",JSON.toJSONString(byProvincesId));
            }
//            取出
            return JSON.parseArray(redisTemplate.opsForValue().get("provincesList"),Provinces.class);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
//        没有获取到锁的进行自己调用直接
        return this.findByProvincesId();
    }
}
